<?php
/**
 * Geocontexter
 * @link http://code.google.com/p/geocontexter/
 * @package Geocontexter
 */

/**
 * Admin index controller
 *
 *
 * @package Geocontexter
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @author Armand Turpel <geocontexter@gmail.com>
 * @version $Rev$ / $LastChangedDate$ / $LastChangedBy$
 */

namespace Gospecies\Controller;

use Zend\View\Model\JsonModel;
use Gospecies\Controller\AbstractIdentityJsonController;


class AjaxAddProjectAttributeGroupJsonController extends AbstractIdentityJsonController
{

    public function indexAction()
    {
        // get logged user
        $this->user = $this->get_identity();

        try {
              $error  = array();
              $params = array();

              $params = array('id_project' => $this->request->getPost()->id_project,
                              'id_group'   => $this->request->getPost()->id_group,
                             );

              // check permission if id_group is "contributor" or above.
              // users of those groups can only update own projects
              //
              if ((isset($this->user->id_group) && ((int)$this->user->id_status == 200))) {
                  if ((int)$this->user->id_group >= 300) {

                      $ProjectGet = $this->CoreModel('ProjectGet');

                      $params2  = array('id_project' => $params['id_project']);

                      $result  = $ProjectGet->run( $params2 );

                      if (isset($result['id_owner'])) {
                          if ($this->user->id_user !== $result['id_owner']) {
                              return new JsonModel(array('error' => 'permission denied'));
                          }
                      } else {
                          return new JsonModel(array('error' => 'id_project dosent exists: ' . $params['id_project']));
                      }
                  }
              } else {
                  return new JsonModel(array('error' => 'permission denied'));
              }


              $ProjectAddAttributeGroups = $this->CoreModel('ProjectAddAttributeGroups');

              $params3  = array('id_project'     => $params['id_project'],
                                'id_attr_groups' => array($params['id_group']));

              $ProjectAddAttributeGroups->run( $params3 );

              return new JsonModel(array('status'     => 'ok',
                                         'id_project' => $params['id_project'],
                                         'id_group'   => $params['id_group']));

        } catch (\Exception $e) {

            $this->default_error = "Error\n File: " . __file__ . "\nLine: " . __line__ . "\nError: " . $e->__toString();

            return new JsonModel(array('error' => $this->default_error));

        }
    }
}
